package com.zhonghong.entrance;

import com.zhonghong.excel.ExcelUtil;
import com.zhonghong.xml.XmlUtil;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 * 由单个Excel文件中包含的键值和Value值直接生成strings.xml文件
 * @author zhonghong.zhangxg
 * @date 2016年7月26日上午9:13:45
 */
public class ExcelDirect2Xml implements ActionListener {
    private XmlUtil xmlUtil = new XmlUtil();
    private ExcelUtil excelUtil = null;

    /**
     * 完成excel文件到strings.xml文件的转换
     * 
     * @param xlsFile : excel文件对象
     * @param dest : 生成的strings.xml存放目录
     * @throws IOException
     */
    public boolean translate(File xlsFile,  File dest)   {
        excelUtil = new ExcelUtil(xlsFile);

        // 得到excel的三列值
        HashMap<Integer, ArrayList<String>> keyAndValues = excelUtil.readSheet();

        // 得到values集合的迭代器
        Iterator<?> it = keyAndValues.entrySet().iterator();
        
        // 得到Excel第一列的键值集合
        Entry<?, ?> keyEntry = (Entry<?, ?>) it.next();
        ArrayList<String> keys = (ArrayList<String>) keyEntry.getValue();
        
        while (it.hasNext()) {
            Entry<?, ?> entry = (Entry<?, ?>) it.next();
            // 列的索引值
            int index = (int) entry.getKey();
            // 得到当前列值得集合
            ArrayList<String> valueStrs = (ArrayList<String>) entry.getValue();

            // 初始化一个新的xml模板
            xmlUtil.initXml();
            // 获取键值集合和value结合中的最小值
            for (int i = 0; i < keys.size(); i++) {
                String value = valueStrs.get(i);
                xmlUtil.addNode(keys.get(i), value);
            }
            try {
                xmlUtil.write2File(dest, "strings" + (index + 1) + ".xml");
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            excelUtil.closeWorkBook();
        }
        return true;
    }
    
//    public static void main(String[] args) {
//        ExcelDirect2Xml util = new ExcelDirect2Xml();
//        try {
//            util.translate(new File("strings.xls"), new File("D://"));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    
    
    private JFrame jf;
    private JPanel contentPane;
    private JButton xmlBtn;
    private JFileChooser fileChooser;
    private File xlsFile;
    

    private static final String TITLE = "由Excel直接生成Xml";
    private static final String XML_BTN_STR = "选择Excel文件";
    private static final int WIDTH = 300;
    private static final int HEIGHT = 100;

    /** 用户工作主目录 */
    private final static String PATH = System.getProperty("user.dir");

    public ExcelDirect2Xml() {
        jf = new JFrame(TITLE);
        jf.setSize(WIDTH, HEIGHT);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        jf.setLocation(screenSize.width / 4, screenSize.height / 4);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
        jf.setResizable(false);

        contentPane = new JPanel();
        jf.setContentPane(contentPane);

        xmlBtn = new JButton(XML_BTN_STR);

        contentPane.add(xmlBtn);

        initListener();
    }

    private void initListener() {
        xmlBtn.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String eventFrom = e.getActionCommand();
        switch (eventFrom) {
            
            case XML_BTN_STR: {
                fileChooser = new JFileChooser(PATH);
                fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                fileChooser.showDialog(new JLabel(), XML_BTN_STR);
                xlsFile = fileChooser.getSelectedFile();
                if (xlsFile == null) {
                    JOptionPane.showMessageDialog(new JButton("确定"), "未选择文件!!");
                    return;
                }
                if (checkFile(xlsFile, "xls") || checkFile(xlsFile, "xlsx")){
                    boolean result = translate(xlsFile, new File(PATH));;
                    if (result) {
                        JOptionPane.showMessageDialog(new JButton("确定"), "生成文件路径为：" + PATH);
                    } else {
                        JOptionPane.showMessageDialog(new JButton("确定"), "失败!!!");
                    }
                }
                break;
            }
        }
    }
    
    
    /**
     * 检查文件格式是否正确
     * 
     * @param file: 要检查的文件
     * @param selfSuffix: 匹配的后缀,如 xls(不包含 . )
     * @return 校验合法返回true, 否则返回false
     */
    private boolean checkFile(File file, String selfSuffix) {
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
        if (!suffix.equalsIgnoreCase(selfSuffix)) { // 选择的文件类型不对
            JOptionPane.showMessageDialog(new JButton("确定"), "文件类型错误！");
            return false;
        } else {
            return true;
        }
    }
}
